const tb = document.querySelector('#tb')
const form = document.querySelector('form')
const btncc = document.querySelector('#btnAcc')
// const a = document.querySelectorAll('a')
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const renderBooks = () => {
  axios.get('/api/getbooks').then(({ data: res }) => {
    const { data } = res
    console.log(data)
    const html = data
      .map((item) => {
        return ` <tr>
        <td>${item.id}</td>
        <td>${item.bookname}</td>
        <td>${item.author}</td>
        <td>${item.publisher}</td>
        <td> <a href="#" data-id=${item.id}>删除</a></td>
      </tr>`
      })
      .join('')
    tb.innerHTML = html
  })
}
renderBooks()
form.addEventListener('submit', function (e) {
  e.preventDefault()
  // 使用./lib/form-serialize.js插件获取表单数据
  const data = serialize(form, { hash: true })
  axios.post('/api/addbook', data).then(({ data: res }) => {
    alert(res.msg)
    if (res.data !== 201) return
    this.reset()
    renderBooks()
  })
})
tb.addEventListener('click', function (e) {
  if ((e.target.tagName = 'A')) {
    let id = e.target.dataset.id
    axios.get('/api/delbook?id=' + id).then(({ data: res }) => {
      renderBooks()
    })
  }
})
btncc.addEventListener('click', function (e) {
  e.preventDefault()
  // console.log(1)
  const data = serialize(form, { hash: true })
  axios.get('/api/getbooks', { params: data }).then(({ data: res }) => {
    console.log(res)
    const data = res.data
    const html = data
      .map((item) => {
        return ` <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td> <a href="#" data-id=${item.id}>删除</a></td>
    </tr>`
      })
      .join('')
    tb.innerHTML = html
  })
})
